<template>
  <div class="home">
    <div class="top-nav">
    </div>
    <div :style="{height:'100vh',width:'100%'}" ref="myEchart"></div>

    <add-product-modal
      :modal-visible="addModalVisible"
      :handle-close="closeAddModal"
      :province="province"
      @add-ok="getDistribution"
    />
    <product-list-modal
      :modal-visible="productListVisible"
      :handle-close="closeProductModal"
      :province="searchProvince"
      @has-delete="getDistribution"
    />
  </div>
</template>

<script>
// @ is an alias to /src
import echarts from 'echarts';
import provinceCoordinate from '../utils/provinceCoordinate';
import AddProductModal from './components/AddProductModal';
import ProductListModal from './components/ProductListModal';
import { getAllDistribution } from '../service/service';

require('echarts/map/js/china.js');

export default {
  name: 'Home',
  components: {
    AddProductModal,
    ProductListModal
  },
  data() {
    return {
      myChart: null,
      addModalVisible: false,
      productListVisible: false,
      province: '',
      searchProvince: '',
      data: []
    };
  },
  beforeDestroy() {
    if (!this.myChart) {
      return;
    }
    this.myChart.off('click');
    this.myChart.dispose();

    this.myChart = null;
  },
  mounted() {
    const self = this;

    this.myChart = echarts.init(this.$refs.myEchart); // 这里是为了获得容器所在位置
    window.onresize = this.myChart.resize;

    this.myChart.on('click', (e) => {
      const { componentSubType, name } = e;
      if (componentSubType === 'map') {
        self.province = name;
        self.addModalVisible = true;
      } else {
        self.searchProvince = name;
        self.productListVisible = true;
      }
    });

    this.getDistribution();
  },
  methods: {
    closeAddModal() {
      this.addModalVisible = false;
    },
    closeProductModal() {
      this.productListVisible = false;
    },
    getDistribution() {
      getAllDistribution().then((res) => {
        const { data } = res.data;
        this.data = data;
      }).finally(() => {
        this.showMap();
      });
    },
    showMap() {
      const self = this;
      this.myChart.setOption({
        backgroundColor: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 1,
          y2: 1,
          colorStops: [{
            offset: 0,
            color: '#0f378f' // 0% 处的颜色
          }, {
            offset: 1,
            color: '#00091a' // 100% 处的颜色
          }],
          globalCoord: false // 缺省为 false
        },
        title: {
          top: 20,
          text: '产品分布',
          subtext: '',
          x: 'center',
          textStyle: {
            color: '#ccc'
          }
        },

        tooltip: {
          trigger: 'item',
          formatter(params) {
            if (typeof (params.value)[2] === 'undefined') {
              return `${params.name} - ${params.value || ''}`;
            }
            return `${params.name} : ${params.value[2]}`;
          }
        },
        legend: {
          orient: 'vertical',
          y: 'bottom',
          x: 'right',
          data: ['pm2.5'],
          textStyle: {
            color: '#fff'
          }
        },
        visualMap: {
          show: false,
          min: 0,
          max: 500,
          left: 'left',
          top: 'bottom',
          text: ['高', '低'], // 文本，默认为数值文本
          calculable: true,
          seriesIndex: [1],
          inRange: {
          }
        },
        geo: {
          map: 'china',
          show: true,
          roam: true,
          label: {
            normal: {
              show: false
            },
            emphasis: {
              show: false,
            }
          },
          itemStyle: {
            normal: {
              areaColor: '#3a7fd5',
              borderColor: '#0a53e9', // 线
              shadowColor: '#092f8f', // 外发光
              shadowBlur: 20
            },
            emphasis: {
              areaColor: '#0a2dae', // 悬浮区背景
            }
          }
        },
        series: [{
          symbolSize: 5,
          label: {
            normal: {
              formatter: '{b}',
              position: 'right',
              show: true
            },
            emphasis: {
              show: true
            }
          },
          itemStyle: {
            normal: {
              color: '#FFFFFF'
            }
          },
          name: 'light',
          type: 'scatter',
          coordinateSystem: 'geo',
          data: self.convertData(self.data),
        },
        {
          type: 'map',
          map: 'china',
          geoIndex: 0,
          aspectScale: 0.75, // 长宽比
          showLegendSymbol: false, // 存在legend时显示
          label: {
            normal: {
              show: false
            },
            emphasis: {
              show: false,
              textStyle: {
                color: '#fff'
              }
            }
          },
          roam: true,
          itemStyle: {
            normal: {
              areaColor: '#031525',
              borderColor: '#FFFFFF',
            },
            emphasis: {
              areaColor: '#2B91B7'
            }
          },
          animation: false,
          data: self.data
        },
        {
          name: 'Top 5',
          type: 'scatter',
          coordinateSystem: 'geo',
          symbol: 'pin',
          symbolSize: [50, 50],
          label: {
            normal: {
              show: true,
              textStyle: {
                color: '#fff',
                fontSize: 9,
              },
              formatter(value) {
                return value.data.value[2];
              }
            }
          },
          itemStyle: {
            normal: {
              color: '#D8BC37', // 标志颜色
            }
          },
          data: self.convertData(self.data),
          showEffectOn: 'render',
          rippleEffect: {
            brushType: 'stroke'
          },
          hoverAnimation: true,
          zlevel: 1
        },
        ]
      });
    },
    convertData(list) {
      const res = [];
      // eslint-disable-next-line no-restricted-syntax
      for (const item of list) {
        const geoCoord = provinceCoordinate[item.name];
        if (geoCoord) {
          res.push({
            name: item.name,
            value: geoCoord.concat(item.value)
          });
        }
      }
      return res;
    }
  }
};
</script>

<style lang="less">
  .home {
    width: 100%;
    height: 100%;
    position: relative;

    .top-nav {
      width: 100%;
      height: 60px;
      position: fixed;
      top: 0;
      background: transparent;
      z-index: 100;
    }
  }
</style>
